package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.net.URLEncoder;
/**
 * 
 * @author msjykf
 * 获取无限天利短信状态报告接口
 *
 */

public class SmsGetRptWxtlTask implements CallBackInvoke{
	private static final Log log=LogFactory.getLog(SmsGetRptWxtlTask.class);
	public void doCallBack(EliteBean eliteBean,String callBack,Map map,String body){
		try {
			PropertiesUtil pt= new PropertiesUtil();
			def userid = Base64.encode(URLEncoder.encode(pt.readValue("wxtl_userid"),"utf-8"),"utf-8"); //短信账号 先URLEncode编码后使用Base64算法加密
			def pwd = Base64.encode(URLEncoder.encode(pt.readValue("wxtl_pwd"),"utf-8"),"utf-8"); //短信密码  先URLEncode编码后使用Base64算法加密
			def ipport = pt.readValue("sms_ip")+":"+pt.readValue("wxtl_port");
			def cnt = 500;
			def url = "http://"+ipport+"/communication/fetchReports.ashx?cid="+userid+"&pwd="+pwd+"&cnt="+cnt;
			log.debug("url:"+url);
			def charset = "utf-8"; //设置字符集
			def timeout = 100000; //设置请求超时时间
			def enableSSLflag = 0;
			def k =0;
			def i = 0;
			def msgjson = "";
			def sqls = "";
			def num =0;
			while(k<3) {
				msgjson = Util.doHttpGet(url,charset,timeout,enableSSLflag);
				//log.debug("msgjson:"+msgjson);
				JSONObject obj = JSONObject.fromObject(msgjson);
				//log.debug("status:"+obj.get("status"));
				if(obj.get("status").equals("0")) {
					JSONArray data = obj.getJSONArray("data");
					//log.debug("data.size():"+data.size());
					k= data.size()>0?k++:3; //无结果则终止循环
					for (i = 0; i < data.size(); i++) {
						JSONObject it = data.get(i);
						//log.debug("it:"+it);
						if(it.get("status").equals("0")) {
							sqls = "prosperitysum=nvl(prosperitysum,0)+1";
						}else {
							sqls = "failuresum=nvl(failuresum,0)+1";
						}
						try { 
							if(!it.get("custom").equals("")) {
								//log.debug("custom:"+it.get("custom"));
								String[] datac=new String[2];
								datac[0] = "update sms_send set rstate="+it.get("status")+",rtime=sysdate,spno='"+it.get("csid")+"',pknum="+it.get("pknumber")+",rdesc='"+it.get("errorcode")+"' where smsno="+it.get("custom")+"";
								datac[1] = "update sms_send_batch sb set "+sqls+" where exists(select 1 from sms_send sd where sb.batch_id=sd.batch_id and sd.smsno="+it.get("custom")+")";
								int[] batchsql = eliteBean.updateBatch(datac,"dataSource");
							};
							num++;
						}catch(Exception e) {
							log.error("ErrorMessage:",e);
						}
					}
				}else {
					k=3;
				}
				log.debug("num:"+num);
			};
		}catch(Exception e) {
			log.error("ErrorMessage:",e);
		}
	}
}